from urllib.parse import quote,urlencode
from urllib.request import Request,urlopen

#拼接url网址
def get_url(word):
    ur1 =  'https://www.baidu.com/s?{}'
    zhuanma = urlencode({'wd':word})
    ur1 = ur1.format(zhuanma)
    return ur1
#发送请求及保存
def request_url(ur1,filename):
    headers = {
        "User-Agent": "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)"
    }
    req = Request(ur1,headers=headers)
    resp = urlopen(req)
    html = resp.read().decode('utf-8')
    with open(filename,"w",encoding='utf-8')as f:
        f.write(html)

if __name__=='__main__':
    word = input("请输入搜索内容")
    ur1 = get_url(word)
    filename = word + '.html'
    request_url(ur1,filename)
